<?php

namespace app\api\controller\wap;

use app\admin\controller\Log;
use app\command\extend\http\ApiCache;
use app\common\model\coin\CoinPlatform;
use app\common\model\feature\communal\File;
//use app\common\model\coin\Coin;
use app\common\model\users\UsersKey;
use mall\library\Huobi;
use mall\utils\Tool;
use think\facade\Db;
use think\facade\Request;

class Coin extends Base
{

    //为了验证地址而添加的 url 前缀
    private $urlValidatePre = '';

    /**
     * 获取首页3大交易对实时行情
     */
    public function market()
    {
        try{

            $coinList = ['btcusdt', 'ethusdt','dotusdt'];
//            $btc = (new Huobi())->get_detail_merged('btcusdt');
//            $eth = (new Huobi())->get_detail_merged('ethusdt');
//            $dot = (new Huobi())->get_detail_merged('dotusdt');
//            \think\facade\Log::log('aaa',$btc);
            if(!$marketTickers = ApiCache::request('GetHistoryOpenAndClose',[
                'codes' => implode(',',$coinList),
            ]))  {
                $marketTickers = (new UsersKey())->getMarketTickers();
            }

            $data = [
                [

                    'name'=>'BTC/USDT',
                    'close'=>$marketTickers['btcusdt']['close'],
                    'up'=>round(100*($marketTickers['btcusdt']['close']-$marketTickers['btcusdt']['open'])/$marketTickers['btcusdt']['close'],2)
                ],
                [
                    'name'=>'ETH/USDT',
                    'close'=>$marketTickers['ethusdt']['close'],
                    'up'=>round(100*($marketTickers['ethusdt']['close']-$marketTickers['ethusdt']['open'])/$marketTickers['ethusdt']['close'],2)
                ],
                [
                    'name'=>'DOT/USDT',
                    'close'=>$marketTickers['dotusdt']['close'],
                    'up'=>round(100*($marketTickers['dotusdt']['close']-$marketTickers['dotusdt']['open'])/$marketTickers['dotusdt']['close'],2)
                ]
            ];
            /*$data = [
                [

                    'name'=>'BTC/USDT',
                    'close'=>$marketTickers['btcusdt']['close'],
                    'up'=>round(100*($marketTickers['btcusdt']['close']-$marketTickers['btcusdt']['open'])/$marketTickers['btcusdt']['close'],2)
                ],
                [
                    'name'=>'ETH/USDT',
                    'close'=>$marketTickers['ethusdt']['close'],
                    'up'=>round(100*($marketTickers['ethusdt']['close']-$marketTickers['ethusdt']['open'])/$marketTickers['ethusdt']['close'],2)
                ],
                [
                    'name'=>'DOT/USDT',
                    'close'=>$marketTickers['dotusdt']['close'],
                    'up'=>round(100*($marketTickers['dotusdt']['close']-$marketTickers['dotusdt']['open'])/$marketTickers['dotusdt']['close'],2)
                ]
            ];*/
            $list = [
                'list'  => $data,
            ];
            return $this->returnAjax("ok",1,$list);
        }catch (\Exception $e) {
            return $this->returnAjax('系统内部错误'.$e->getMessage(),0);
        }

    }

    public function list() {
        try{
            $type = Request::get('type',0,'intval');
            $platform = Request::get('platform',1,'intval');
            $userid = \mall\basic\Users::get('id');
            $page = Request::get('page',0,'intval');
            $page = $page > 0?$page:1;
            $pageSize = Request::get('pagesize',15,'intval');
            //p($coinPlatform);exit;
            $coinModel = (new \app\common\model\coin\Coin());
            $coinRuleModel = (new \app\common\model\coin\CoinRule());
            $coinPlatform = CoinPlatform::where('status', 1)->select()->toArray();
            $model = $coinRuleModel->alias('coin_rule');
            $model->where('coin.status',"=",$coinModel::STATUS_OPEN);
            $model->where('coin.platform',"=",$platform);
            //$model->where('coin_rule.is_open',"=",$coinRuleModel::STATUS_OPEN);
            $model->where('coin_rule.user_id',"=",$userid);
            if($type>0) {
                $model->where('coin_rule.type',"=",$type);
            }
            $coinRuleList= $model
                ->join('coin coin','coin.id=coin_rule.coin_id','INNER')
                ->join('coin_rule_run run_details','run_details.id=coin_rule.coin_rule_run_id AND run_details.unique_id=run_details.coin_rule_id','LEFT')
                ->field([
                    'coin.id','coin.name','coin.code',
                    'coin_rule.type','coin_rule.coin_id','coin_rule.first_amount','coin_rule.num','coin_rule.stop_profit_ratio','coin_rule.stop_profit_callback',
                    'run_details.unique_id','run_details.cover_times','run_details.cover_times_auto',
                    'run_details.cover_times_manual','run_details.amount','run_details.quantity','run_details.unit_price','run_details.version'
                ])
                ->select();
            $coinRuleList = $coinRuleList?$coinRuleList->toArray():[];
            $coin_ids = $model->column('coin_id');
            $coinList = $coinModel->field('id,name,code,order_num')
                ->where([['status','=',$coinModel::STATUS_OPEN],['platform','=',$platform]])
                ->where('id','in',$coin_ids)
                ->limit(($page-1)*$pageSize,$pageSize)
                ->select();

            $coinList = $coinList?$coinList->toArray():[];
            if($coinRuleList && $coinList) {
                if(!$marketTickers = ApiCache::request('GetHistoryOpenAndClose',[
                    'codes' => implode(',',array_column($coinList,'code')),
                ]))  {
                    $marketTickers = (new UsersKey())->getMarketTickers();
                }
                $coinList = array_column($coinList,null,'id');
                $coinRuleList = $coinRuleList?array_column($coinRuleList,null,'coin_id'):[];
                $tmpList = $issets = $orderNum = $isOpen = [];
                foreach ($coinList as $key=>$value) {
                    $id = $value['id'];
                    $tmpList[$id]['name'] = strtoupper($value['name']);
                    $value['name'] = strtoupper($value['name']);
                    if(isset($coinRuleList[$value['id']])) {
                        $arrCoinRule = $coinRuleList[$value['id']];
                        $tmpList[$id]['id'] = $id;
                        $tmpList[$id]['num'] = sprintf("%.8f",$arrCoinRule['quantity']);
                        $tmpList[$id]['label'] = $coinRuleModel::getTypeText($arrCoinRule['type']);
                        //涨幅
                        //$tmpList[$id]['increase'] = bcdiv(100*($marketTickers[$value['code']]['close'] -$arrCoinRule['unit_price']),$arrCoinRule['unit_price'],2);
                        $tmpList[$id]['increase'] = ($arrCoinRule['unit_price']>0)?bcdiv(100*($marketTickers[$value['code']]['close'] -$arrCoinRule['unit_price']),$arrCoinRule['unit_price'],2):0;
                        //浮亏
                        $tmpList[$id]['profit'] = bcmul($tmpList[$id]['increase']*0.01,$arrCoinRule['amount'],2);
                        $tmpList[$id]['isset'] = 1;
                        $issets[]= $tmpList[$id]['isset'];
                        $orderNum[]= $value['order_num'];
                        $isOpen[]= 1;
                    } else {
                        if($type>0) {
                            unset($tmpList[$id]);
                        } else {
                            $tmpList[$id]['id'] = $id;
                            $tmpList[$id]['num'] = sprintf("%.8f",0);
                            $tmpList[$id]['label'] = '未开启';
                            $tmpList[$id]['profit'] = 0;
                            $tmpList[$id]['increase'] = 0;
                            $tmpList[$id]['isset'] = 0;
                            $issets[]= $tmpList[$id]['isset'];
                            $orderNum[]= $value['order_num'];
                            $isOpen[]= 0;
                        }
                    }
                }
                //p($coinList);exit;
                array_multisort($issets, SORT_DESC,$orderNum, SORT_ASC,$isOpen, SORT_DESC, $tmpList);
                //查询账户余额
                $data['list'] = array_values($tmpList);
            } else {
                $data['list'] = [];
                //return $this->returnAjax("暂无数据",0,$data);
            }
            $data['platform'] = $coinPlatform[$platform]['id'];
            $data['platform_list'] = $coinPlatform;
            return $this->returnAjax("ok",1,$data);
        }catch (\Exception $e) {
            return $this->returnAjax('系统内部错误'.$e->getMessage(),0);
        }

    }

}
